#include <kernel.h>

int
kthread_init(void)
{
	 return 0;
}

struct kthread_priv_s
{
	 void (*init) (void *arg);
	 void  *arg;
	 int    event_loop;
};

static void
_kthread_entry(void *_)
{
	 struct kthread_priv_s *priv = (struct kthread_priv_s *)_;
	 proc_priv_set(priv);
	 proc_self_type_set(PROC_TYPE_KTHREAD);
	 
	 if (priv->init) priv->init(priv->arg);
	 if (priv->event_loop)
		  while (1)
		  {
			   proc_event_process_irq_save();
			   proc_to_wait();
			   intr_irq_restore_schedule();
		  }
}

proc_t
kthread_create(const char *name, uint32_t level, uint32_t stack_size, void (*init) (void *arg), void *arg, int event_loop)
{
	 struct kthread_priv_s *priv = (struct kthread_priv_s *)ekf_alloc(sizeof(struct kthread_priv_s));
	 if (priv == NULL) return NULL;
	 
	 priv->init       = init;
	 priv->arg        = arg;
	 priv->event_loop = event_loop;
	 
	 proc_t p = proc_create(name, level, stack_size, proc_kvpt_get(), _kthread_entry, priv);
	 if (p == NULL)
	 {
		  ekf_free(priv);
		  return NULL;
	 }

	 return p;
}
